<!-- eslint-disable vue/html-self-closing -->
<template>
  <div class="image-upload">
    <el-upload
      action="#"
      list-type="picture-card"
      :file-list="fileList"
      :on-preview="handlePreview"
      :limit="limit"
      :class="{ isDisabled: isLimit }"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :http-request="httpRequest"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog
      title="预览大图"
      :visible="showdialog"
      @close="showdialog = false"
    >
      <img :src="showImg" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import cos from '@/utils/cos'
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      fileList: [],
      showdialog: false,
      showImg: ''
    }
  },
  computed: {
    isLimit () {
      return this.fileList.length >= this.limit
    },
    isSuccessUpload () {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    handlePreview (file) {
      this.showdialog = true
      this.showImg = file.url
    },
    handleRemove (file, fileList) {
      // console.log(fileList)
      // 第一种写法
      // this.fileList = [...fileList]
      // 第二种写法
      this.fileList = this.fileList.filter(item => {
        return item.uid !== file.uid
      })
    },
    handleChange (file, fileList) {
      this.fileList = [...fileList]
    },
    httpRequest ({ file }) {
      const fileObj = this.fileList.find(item => item.uid === file.uid)
      // status 值为 uploading 时 显示进度条
      fileObj.status = 'uploading'
      cos.putObject(
        {
          Bucket: 'seventeen-1314261668' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-beijing' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key:
            +new Date() +
            '-' +
            file.name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          Body: file /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */,
          // 上传进度
          onProgress: progressData => {
            // console.log(JSON.stringify(progressData))
            // percentage 控制进度条
            fileObj.percentage = progressData.percent * 100
          }
        },
        (err, data) => {
          // console.log(err || data)
          if (err) {
            this.$message.error('上传失败')
            return
          }
          fileObj.url = 'https://' + data.Location
          // 定时器 更好的显示进度条
          setTimeout(() => {
            fileObj.status = 'success'
          }, 500)
        }
      )
    },
    beforeUpload ({ size, type }) {
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.includes(type)) {
        this.$message.error('文件格式不正确')
        return false
      }
      // 限制文件大小
      if (size / 1024 / 1024 > 5) {
        this.$message.error('上传头像过大, 超过了5M, 必须5M以内')
        return false
      }
      return true
    }
  }
}
</script>

<style lang="scss" scoped>
.isDisabled {
  width: 100%;
  height: 100%;
  ::v-deep .el-upload--picture-card {
    display: none !important;
  }
}
</style>
